﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace SU.Center.Api
{
    /// <summary>
    /// JWT 令牌生成器
    /// </summary>
    public class JwtTokenGenerator : IJwtTokenGenerator
    {
        private const string SecretKey = "jPfQnRBKXPG1EKQCTZTbDSfR3kz2AKPG"; // 请更换为你的密钥
        private const double ExpirationMinutes = 60; // 过期时间（分钟）

        public string GenerateToken(int userId, string username)
        {
            // 创建密钥
            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // 创建声明
            var claims = new[]
        {
            new Claim("username", username),
            new Claim("userId", userId.ToString())
            // 可以添加其他声明
        };

            // 创建 JWT 头部和载荷
            var token = new JwtSecurityToken(
                issuer: "SU.Center.Api", // 发行者
                audience: "SU.Center.Api", // 受众
                claims: claims,
                expires: DateTime.Now.AddMinutes(ExpirationMinutes),
                signingCredentials: creds);

            // 返回 JWT 字符串
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
